package light.head.framework.utils;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

/**
 * @author 简航 创建日期 Jan 5, 2009 11:05:15 AM
 */
public class XmlUtils {

	public static Document loadXML(File file) {
		return null;
	}

	synchronized public static Document loadXML(InputStream in) {
		Document document = null;
		SAXReader reader = new SAXReader();
		try {
			document = reader.read(in);
			return document;

		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	synchronized public static Document loadXML(String filePath) {
		InputStream inputStream = XmlUtils.class
				.getResourceAsStream(filePath);
		return loadXML(inputStream);
	}
	
	
	public static Document loadConfigFromXML(String path) {
		return loadXML(XmlUtils.class.getResourceAsStream(path));
	}

	/**
	 * 查询二级节点(未完成)
	 * @param 要查询的根节点
	 * @param 二级节点tagName
	 * @return 二级节点列表
	 * @author 简航
	 * 创建日期 Jan 5, 2009 11:26:39 AM
	 */
	public static String getSubnodeValue(Node parent, String subnode) {
		return null;
	}
	
	/**
	 * 根据Attr=ID参数获取Element对象
	 * @param 要获取的父级Element
	 * @param 要获取的Element Attr=ID  的值
	 * @return Element对象
	 * @author 简航
	 * 创建日期 2010-03-12 10:07:15
	 */
	@SuppressWarnings("rawtypes")
	public static Element getElementByAttrId(Element e, String id) {
		
		Element pei = null;
		for (Iterator pe = e.elementIterator(); pe.hasNext();) {
			pei = (Element) pe.next();
			if (pei.attributeValue("id") != null && pei.attributeValue("id").equals(id))
				return pei;
			else {
				Element te = getElementByAttrId(pei, id);
				if (te != null)
					return te;
			}
		}
		return null;
	}
	
	/**
	 * 保存Document对象到指定路径
	 * @param 目标路径
	 * @param Document对象
	 * @return 是否保存成功
	 */
	public static Boolean saveXML(String path, Document doc) {
		try {
			OutputFormat format = OutputFormat.createPrettyPrint();
			format.setEncoding("GBK");
			XMLWriter write = new XMLWriter(new FileWriter(new File(path)), format);
			write.write(doc);
			write.close();
			
			return true;
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		}
	}
}
